package org.perche.chat.server.service;

import org.apache.thrift.TException;
import org.perche.chat.shared.FieldVerifier;
import org.perche.chat.thrift.data.GreetingRequest;
import org.perche.chat.thrift.data.GreetingResponse;
import org.perche.chat.thrift.services.GreetingService;


public class GreetingServiceImpl implements GreetingService.Iface {

	public GreetingResponse greetServer(GreetingRequest request)
			throws TException {
		// Verify that the input is valid. 
				if (!FieldVerifier.isValidName(request.getGreetingRequest().getName())) {
					// If the input is not valid, throw an IllegalArgumentException back to
					// the client.
					throw new IllegalArgumentException(
							"Name must be at least 4 characters long");
				}

				String serverInfo = request.getServerInfo();
				String userAgent = request.getUserAgent();

				// Escape data from the client to avoid cross-site script vulnerabilities.
				String input = escapeHtml(request.getGreetingRequest().getName());
				userAgent = escapeHtml(userAgent);
				
				GreetingResponse response = new GreetingResponse();

				response.setGreetingResponse("Hello, " + input + "!<br><br>I am running " + serverInfo
						+ ".<br><br>It looks like you are using:<br>" + userAgent);
				
				return response;
			}

			/**
			 * Escape an html string. Escaping data received from the client helps to
			 * prevent cross-site script vulnerabilities.
			 * 
			 * @param html the html string to escape
			 * @return the escaped string
			 */
			private String escapeHtml(String html) {
				if (html == null) {
					return null;
				}
				return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
						.replaceAll(">", "&gt;");
			}

}
